import React, {Component, Fragment } from 'react';
import {
  Form,
  Input,
  Modal,
  Button,
  Table,
  Row, Col, Divider, Select
} from 'antd/lib/index';
import TextArea from 'antd/es/input/TextArea';
import { connect } from 'dva/index';
import { microList } from '../services/micro';
const FormItem = Form.Item;
const { Option } = Select;

let num = 0;
const entityNameSpace = 'module';
@connect(({ module, loading }) => ({
  module,
  loading: loading.models.module,
}))
class ModularInfoForm extends Component {
  completeCallBack;
  projectId;

  state = {
    visible: false,
    radioDisable: false,
    projectInfo: {},
    databaseList: [],
    microData:[]
  };

  columns = [
    {
      title: '程序名称',
      dataIndex: 'name',
    },
    {
      title: '显示名称',
      dataIndex: 'showName',
    },
    {
      title: '简介',
      dataIndex: 'description',
    },
    {
      title: '操作',
      render: (text, record) => (
        <Fragment>
          <a
            onClick={this.handleEntityFormModalVisible.bind(this, true, record.id)}
          >
            修改
          </a>
          <Divider type="vertical"/>
          <a onClick={this.handleRemoveEntity.bind(this, record)}>删除</a>
        </Fragment>
      ),
    },
  ];


  componentDidMount() {
    this.props.onRef(this);
  }


  updateColums = () => {
    this.columns.splice(0,0,{
      title: '微服务名称',
      dataIndex: 'microId',
      render:text => {
        const { microData } =this.state;
       let name = '';
        microData.forEach(value => value.id === text ? name=value.name:'')
        return <span>{name}</span>
      }
    },)
  };

  handleReloadTableList = () => {
    const { dispatch,projectId,proType } = this.props;

    dispatch({
      type: `${entityNameSpace}/queryEntityPageList`,
      payload: { projectId : projectId },
    });

    microList({ projectId : projectId }).then(res => this.setState({microData:res.data}))

    if (proType === 'micro' && num === 0){
      num = 1;
      this.updateColums();
    }
  };

  handleEntityFormModalVisible = (flag, entityId) => {

    const { dispatch } = this.props;

    if (flag && entityId) {
      dispatch({
        type: `${entityNameSpace}/detailEntity`,
        payload: { id: entityId },
      });
    } else {
      dispatch({
        type: `${entityNameSpace}/changeDetailEntity`,
        payload: {},
      });

    }
  };

  handleRemoveEntity = record => {
    const { dispatch } = this.props;

    Modal.confirm({
      title: '确认',
      content: '是否确认删除',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        dispatch({
          type: `${entityNameSpace}/removeEntity`,
          payload: record,
          callback: () => {
            this.handleReloadTableList();
          },
        });
      },
    });
  };


  handleModalVisible = (visible, callBack, id) => {
    this.completeCallBack = callBack;
    const { form } = this.props;
    this.setState({
      ...this.state,
      visible: visible,
      radioDisable: id ? true : false,
      projectInfo: {},
    });
    if (visible) {
      // form reset
      form.resetFields();
      this.projectId = id;
      this.handleReloadTableList();
      this.handleEntityFormModalVisible(false);
    }
  };


  handleSearch = () => {
    const { form } =this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      this.handleEntityUpdate(fieldsValue);
    });
  };

  handleEntityUpdate = fieldsValue => {
    const { dispatch, [entityNameSpace]: { entityInfoObj } ,projectId } = this.props;

    let formData = {...fieldsValue,projectId:projectId};
    if (entityInfoObj.id) {
      formData = {
        ...fieldsValue,
        id: entityInfoObj.id
      };
    }

    dispatch({
      type: `${entityNameSpace}/updateEntity`,
      payload: formData,
      callback: () => {
        this.handleEntityFormModalVisible(false);
        this.handleReloadTableList();
      },
    });
  };


  handleCancel = () => {
    this.setState({
      ...this.state,
      visible: false
    });
  };


  renderSimpleForm() {
    const {
      form, [entityNameSpace]: { entityInfoObj },proType
    } = this.props;
    const { microData } =this.state;
    return (
      <Form >
        <Row gutter={16}>
          {proType === 'micro' ?
          <Col span={5}>
            <FormItem>
            {form.getFieldDecorator('microId', {
              initialValue: entityInfoObj.microId,
              rules: [{
                required: true,
                message: '请选择程序名称！'
              }],
            })( <Select placeholder='微服务名称' style={{ width: '100%' }}>
              {microData.map(v=>(
              <Option value={v.id}>{v.name}</Option>
              ))}
                </Select>)}
            </FormItem>
          </Col>:''}
          <Col span={5}>
            <FormItem>
              {form.getFieldDecorator('name', {
                initialValue: entityInfoObj.name,
                rules: [{
                  required: true,
                  message: '请输入程序名称！'
                }],
              })(<Input placeholder="程序名称"/>)}
            </FormItem>
          </Col>
          <Col span={5}>
            <FormItem>
              {form.getFieldDecorator('showName', {
                initialValue: entityInfoObj.showName,
                rules: [{
                  required: true,
                  message: '请输入显示名称！'
                }],
              })(<Input placeholder="显示名称"/>)}
            </FormItem>
          </Col>
          <Col span={5}>
            <FormItem>
              {form.getFieldDecorator('description', {
                initialValue: entityInfoObj.description,
                rules: [{
                  required: true,
                  message: '请输入简介！'
                }],
              })(<TextArea placeholder="简介"/>)}
            </FormItem>
          </Col>
          <Col span={4}>
            <Button type="primary" onClick={()=> this.handleSearch()}>
              添加
            </Button>
          </Col>
        </Row>
      </Form>
    );
  }

  render() {

    const { visible } = this.state;
    const { [entityNameSpace]: { entityPageResult },
    } = this.props;
    let data =[];
    if (entityPageResult.list){
      data = entityPageResult.list;
    }

    return (
      <Modal
        width={1000}
        visible={visible}
        keyboard={false}
        maskClosable={false}
        title="模块管理"
        onCancel={this.handleCancel}
        footer={[
          <Button key="back" onClick={this.handleCancel}>
            关闭
          </Button>
        ]}
      >
        {this.renderSimpleForm()}
        <br />
        <Table
          rowKey="id"
          bordered={false}
          onRow={false}
          pagination={false}
          cellspaceing={50}
          dataSource={data}
          columns={this.columns}
        />

      </Modal>
    );
  }
}

export default Form.create()(ModularInfoForm);
